/*
 * Description: 工具类
 */
#include "stability_common.h"
#include <windows.h>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <ctime>
#include "log.h"
#include "cJSON.h"
#pragma comment(lib, "wevtapi.lib")

namespace DFX {
const std::string REG_SZ_INVAILD_VALUE = " - ";
constexpr auto REG_VALUE_MAX_LENGTH = 256;
constexpr DWORD REG_DWORD_INVAILD_VALUE = 0x7fffffff;
constexpr int FILE_TIME_SHIFT_AMOUNT = 32;
const int HOURS_IN_DAY = 24;
const int MAX_DAYS_IN_MONTH = 31;

std::string StabilityCommon::MapToJson(const std::map<std::string, std::string> &data)
{
    cJSON *root = nullptr;
    cJSON *item = nullptr;
    std::string jsonString;
    root = cJSON_CreateObject();
    if (root == NULL) {
        LOG_ERR("[DFX - Stability] - cJSON_CreateObject failed");
        return "";
    }
    // 遍历 map 并向 JSON 对象添加键值对
    for (const auto &it : data) {
        item = cJSON_CreateString(it.second.c_str());
        if (item != nullptr) {
            cJSON_AddItemToObject(root, it.first.c_str(), item);
        }
    }
    char *raw_json = cJSON_PrintUnformatted(root);

    if (raw_json != nullptr) {
        jsonString = string(raw_json);
        free(raw_json);
    } else {
        LOG_ERR("[DFX - Stability] - cJSON_PrintUnformatted failed");
    }
    cJSON_Delete(root);
    return jsonString;
}

// 去除字符串两端的空白字符
std::string StabilityCommon::StringTrimAll(const std::string &str)
{
    size_t start = str.find_first_not_of(" \t\n\r\f\v");
    if (start == std::string::npos) {
        return "";
    }
    size_t end = str.find_last_not_of(" \t\n\r\f\v");
    return str.substr(start, end - start + 1);
}

std::string StabilityCommon::LPCWSTRToString(LPCWSTR wstr)
{
    if (wstr == nullptr) {
        return "";
    }
    int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    if (len == 0) {
        return ""; // 转换失败时返回空字符串
    }
    // 分配缓冲区并进行转换
    std::string str(len - 1, '\0'); // -1 是为了去掉末尾的 null 字符
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &str[0], len, NULL, NULL);
    return str;
}
}